package com.julis.download;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.net.URL;

import com.julis.base.BaseApplication;
import com.julis.html_analyse.PackageTool;
import com.julis.html_analyse.UpdateHelper;
import com.julis.html_analyse.XORPackageKey;


public class Downloader {
    private Context context;
    private ZYDownloading zyDownloading;
    private CustomDialog builder = null;
    private String downloadUrl;
    private String fileMD5;
    Handler myHander;

    public Downloader(Context context, String downloadUrl, String fileMD5,  Handler myHander) {
        super();
        this.context = context;
        this.downloadUrl = downloadUrl;
        this.fileMD5 = fileMD5;
        this.myHander = myHander;
    }

    public void tryToUpdate(String message, String title) {
        showUpdateDialog(message, title, downloadUrl);
    }


    private void showUpdateDialog(String message, String title,
                                  final String downloadUrl) {
        zyDownloading = new ZYDownloading(context);
        builder = new CustomDialog.Builder(context)
                .setContentView(zyDownloading)
                .setTitle(title)
                .setPositiveButton("立即更新",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                try {
                                    downLoadUpdateFile(downloadUrl, builder);
                                } catch (Exception e) {
                                    if (builder != null) {
                                        builder.dismiss();
                                    }
                                    e.printStackTrace();
                                }
                            }
                        })
                .setNegativeButton("以后再说",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (builder != null) {
                                    builder.dismiss();
                                }

                            }
                        }).create();
        builder.show();
    }

    String localPathda = "";
    String pathFiles = "";
    private String path = "";

    private void downLoadUpdateFile(final String url,
                                    final CustomDialog builder2) throws Exception {
        zyDownloading.startDownload();
        builder2.getButton_Layout().setVisibility(View.INVISIBLE);
        // 网络文件地址
        String urlString = url;
        path = url;
        // 本地存储的路径
        String localPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/local";
        localPathda = localPath;
        // 本地存储的文件名
        final File pathFile = new File(getPath());
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        URL mUrl = new URL(urlString);
        String localName = new File(mUrl.getFile()).getName();
        pathFiles = localName;
        final int[] max = new int[1];
        if (!TextUtils.isEmpty(localName)) {
            // 实例化下载工具，参数为：网络文件地址，本地存储路径，本地存储文件名，线程数量，上下文菜单
            final DownloadUtil mDownloadUtil = new DownloadUtil(urlString,
                    localPath, localName, 3, context);


            mDownloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {

                @Override
                public void downloadStart(int fileSize) {
                    max[0] = fileSize;
                    Log.d("cz", "downloadStart");
                }

                @Override
                public void downloadProgress(int downloadedSize) {
                    zyDownloading.setProgress((int) downloadedSize * 100
                            / max[0]);
                    if (downloadedSize % 10 == 0) {
                        Log.d("cz", "下载中:" + (int) downloadedSize * 100
                                / max[0] + "%");
                    }
                }

                @Override
                public void downloadError(int code, String message, Exception e) {
                    zyDownloading.errorDonwloading();
                    Toast.makeText(context, message,
                            Toast.LENGTH_SHORT).show();
                    builder2.getMyNegativeButton().setText("确定");
                    builder2.getMyPositiveButton().setText("重新下载");
                    builder2.getMyPositiveButton().setOnClickListener(
                            new View.OnClickListener() {
                                public void onClick(View v) {
                                    try {
                                        downLoadUpdateFile(url, builder2);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                    builder2.getButton_Layout().setVisibility(View.VISIBLE);
                }

                @Override
                public void downloadEnd() {
                    Log.d("cz", "downloadEnd");
                    zyDownloading.stopDownloading();
                    // URL mUrl;
                    try {
                        // mUrl = new URL(path);
                        // String fileName = new File(mUrl.getFile()).getName();
                        Log.d("lj", localPathda + "/" + pathFiles);
                        String apkPath = localPathda + "/" + pathFiles;

                        context.sendBroadcast(new Intent("com.bitter.install")
                                .putExtra("apkpath", localPathda + "/"
                                        + pathFiles));
                        if (GetMD5Util.getFileMd5(apkPath).equals(fileMD5)) {
                            install(context, localPathda + "/"
                                    + pathFiles);
                        } else {
                            Log.e("lj", "安装APK检验发现MD5与服务器不一致");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
            mDownloadUtil.start();
        }
    }

    public static final String DOWNLOAD_FOLDER_NAME = "deya/apkfile";
    public static final String DOWNLOAD_FILE_NAME = "gankong.apk";

    private String getPath() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); //
        if (sdCardExist) {
            return new StringBuilder(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()).append(File.separator)
                    .append(DOWNLOAD_FOLDER_NAME).append(File.separator)
                    .toString();
        }
        return "";
    }

    /**
     * @param context
     * @param filePath apk安装
     * @return
     */
    private boolean install(Context context, final String filePath) {
//		Intent i = new Intent(Intent.ACTION_VIEW);
//		File file = new File(filePath);
//		if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
//			i.setDataAndType(Uri.parse("file://" + filePath),
//					"application/vnd.android.package-archive");
//			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			context.startActivity(i);
//			android.os.Process.killProcess(android.os.Process.myPid()); //
//			System.exit(0); //
//			return true;
//		}

        /**
         * 安装apk
         *
         * @param packagePath
         *            路径
         */
        if (filePath == null || filePath.equals("")) {
            return false;
        }
        // 先判断签名是否一直，如果一直直接安装，如果不一致先卸载再安装
        boolean isSample = XORPackageKey.verifySignature(
                BaseApplication.getInstance(),  BaseApplication.getInstance().getPackageName(), filePath);
        Log.e("tag", "升级文件与当前应用签名是否一致：" + isSample);
        if (isSample) {// 如果一致
            new Thread() {
                public void run() {
                    if (PackageTool.install(filePath,
                            BaseApplication.getInstance())) {
                        Message mymessage = new Message();
                        mymessage.what = 10;
                        myHander.handleMessage(mymessage);
//                        Toast.makeText(BaseApplication.getInstance(), "安裝成功", Toast.LENGTH_LONG).show();
                    } else {
                        Message mymessage = new Message();
                        mymessage.what = 11;
                        myHander.handleMessage(mymessage);
//                        Toast.makeText(BaseApplication.getInstance(), "安裝失败", Toast.LENGTH_LONG).show();
                    }
                }


            }.start();
        } else {
            Message mymessage = new Message();
            mymessage.what = 12;
            myHander.handleMessage(mymessage);
//            Toast.makeText(BaseApplication.getInstance(), "签名验证不一致，请联系管理员", 0).show();
        }


        return false;
    }
}
